package org.jeecg.modules.sggg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgTreatmentAssist;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgTreatmentAssistService;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 三高协诊
 * @Author: jeecg-boot
 * @Date: 2022-10-26
 * @Version: V1.0
 */
@Api(tags = "三高协诊")
@RestController
@RequestMapping("/sggg/sgTreatmentAssist")
@Slf4j
public class SgTreatmentAssistController extends JeecgController<SgTreatmentAssist, ISgTreatmentAssistService> {

    @Autowired
    private ISgTreatmentAssistService sgTreatmentAssistService;

    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDepartService sysDepartController;


    @ApiOperation(value = "三高协诊-待转诊分页列表查询", notes = "三高协诊-待转诊分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgTreatmentAssist>> queryPageList(SgTreatmentAssist sgTreatmentAssist,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        // 当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // SysRole role = sysRoleController.getUserRole(loginUser.getId()).getResult();
        List<SysRole> roleList = sysRoleService.getUserRole(sysUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin")) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            // 机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                // queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
                // queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }

        String orgCode = sysUser.getOrgCode();
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryList(page, sgTreatmentAssist,
                orgCode, sysUser.getId(), code);
        return Result.OK(pageList);
    }


    /**
     * 村医的上转列表
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "三高协诊-待转诊分页列表查询", notes = "三高协诊-待转诊分页列表查询")
    @GetMapping(value = "/listByCunyi")
    public Result<IPage<SgMember>> listByCunyi(SgMember sgMember,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        // 当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前挡路用户的角色编码
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        // 村医查询的是所有的用户，但是这个地方先不判断角色了，因为这个菜单这个接口只给村医开放，别的人都不开放
        // 只查询本机构下所有的居民就行了
        QueryWrapper<SgMember> queryWrapper = new QueryWrapper<>();

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            SysUser sysUser1 = sysUserService.getById(sysUser.getId());
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                queryWrapper.eq("doctor_id", sysUser.getId().toString());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            queryWrapper.eq("sys_org_code", sysUser.getOrgCode());

        } else {
            queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
        }


        // queryWrapper.eq(SgMember::getSysOrgCode, loginUser.getOrgCode());

        Page<SgMember> page = new Page<>(pageNo, pageSize);
        IPage<SgMember> pageList = sgMemberService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "查询居民待转诊记录列表", notes = "查询居民待转诊记录列表")
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgTreatmentAssist>> queryByMemberIdList(
            @RequestParam(name = "member_id") String member_id,
            @RequestParam(name = "status") String status) {
        List<SgTreatmentAssist> pageList = sgTreatmentAssistService.selectyByMemberIdList(member_id, status);
        if (pageList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(pageList);
    }


    /**
     * 村医的上转列表
     * @param sgTreatmentAssist
     * @param pageNo
     * @param pageSize
     * @return
     */
   /* @ApiOperation(value = "三高协诊-待转诊分页列表查询", notes = "三高协诊-待转诊分页列表查询")
    @GetMapping(value = "/listByCunyi")
    public Result<IPage<SgTreatmentAssist>> listByCunyi(SgTreatmentAssist sgTreatmentAssist,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        //当前用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //SysRole role = sysRoleController.getUserRole(loginUser.getId()).getResult();
        List<SysRole> roleList = sysRoleService.getUserRole(loginUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin") ) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            //机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }

        String orgCode = loginUser.getOrgCode();
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryList(page, sgTreatmentAssist,
                orgCode, loginUser.getId(), code);
        return Result.OK(pageList);
    }

*/

    /**
     * 待协诊分页列表查询
     *
     * @param sgTreatmentAssist 对象
     * @param pageNo            当前页
     * @param pageSize          页大小
     * @return 当前页数据
     */
    @ApiOperation(value = "三高协诊-代协诊分页列表查询", notes = "三高协诊-代协诊分页列表查询")
    @GetMapping(value = "/receiveList")
    public Result<IPage<SgTreatmentAssist>> queryReceivePageList(SgTreatmentAssist sgTreatmentAssist,
                                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        // 当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // SysRole role = sysRoleController.getUserRole(loginUser.getId()).getResult();
        List<SysRole> roleList = sysRoleService.getUserRole(sysUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin")) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            // 机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                // queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
                // queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }

        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        String orgCode = sysUser.getOrgCode();
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryReceiveList(page, sgTreatmentAssist,
                orgCode, code, sysUser.getId());
        return Result.OK(pageList);
    }


    /**
     * 治疗中分页列表查询
     *
     * @param sgTreatmentAssist 对象
     * @param pageNo            当前页
     * @param pageSize          页大小
     * @return 当前页数据
     */
    @ApiOperation(value = "三高协诊-治疗中分页列表查询", notes = "三高协诊-治疗中分页列表查询")
    @GetMapping(value = "/treatmentList")
    public Result<IPage<SgTreatmentAssist>> queryTreatmentPageList(SgTreatmentAssist sgTreatmentAssist,
                                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        // 当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {

            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setOrgCode(sysUser1.getOrgCode());
//                queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            sysUser.setOrgCode(sysUser1.getOrgCode());

        } else {
            sysUser.setOrgCode(sysUser1.getOrgCode());
        }


        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        String orgCode = sysUser.getOrgCode();
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryTreatmentList(page, sgTreatmentAssist, orgCode, roleCode, sysUser.getId());
        return Result.OK(pageList);
    }

    /**
     * 上转转诊单查询
     *
     * @param sgTreatmentAssist 对象
     * @param pageNo            当前页
     * @param pageSize          页大小
     * @return 当前页数据
     */
    @ApiOperation(value = "三高协诊-上转转诊单查询", notes = "三高协诊-上转转诊单查询")
    @GetMapping(value = "/referralUpList")
    public Result<IPage<SgTreatmentAssist>> queryReferralUpPageList(SgTreatmentAssist sgTreatmentAssist,
                                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryUpReferralList(page, sgTreatmentAssist);
        return Result.OK(pageList);
    }

    /**
     * 下转转诊单查询
     *
     * @param sgTreatmentAssist 对象
     * @param pageNo            当前页
     * @param pageSize          页大小
     * @return 当前页数据
     */
    @ApiOperation(value = "三高协诊-下转转诊单查询", notes = "三高协诊-下转转诊单查询")
    @GetMapping(value = "/referralDownList")
    public Result<IPage<SgTreatmentAssist>> queryReferralDownPageList(SgTreatmentAssist sgTreatmentAssist,
                                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgTreatmentAssist> page = new Page<>(pageNo, pageSize);
        IPage<SgTreatmentAssist> pageList = sgTreatmentAssistService.queryDownReferralList(page, sgTreatmentAssist);
        return Result.OK(pageList);
    }

    @AutoLog(value = "三高协诊-添加")
    @ApiOperation(value = "三高协诊-添加", notes = "三高协诊-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgTreatmentAssist sgTreatmentAssist) {
        sgTreatmentAssistService.save(sgTreatmentAssist);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "三高协诊-编辑")
    @ApiOperation(value = "三高协诊-编辑", notes = "三高协诊-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgTreatmentAssist sgTreatmentAssist) {
        System.out.println("这是内容" + sgTreatmentAssist);
        // 当前用户 发送方信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 当前用户 发送方部门信息
        SysDepart sysDepart = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("org_code", loginUser.getOrgCode()));

        // 患者信息
        SgMember member = this.sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id", sgTreatmentAssist.getMemberId()));

        // 上转
        if (sgTreatmentAssist.getStatus() == 1) {
            // 接收方机构管理员用户
            List<SysUser> adminUserList = this.sgTreatmentAssistService.getAdminUser(sgTreatmentAssist.getHospitalId());
            for (SysUser u : adminUserList) {

                MessageDTO messageDTO = new MessageDTO(loginUser.getUsername(), u.getUsername(), "上转消息提醒", sysDepart.getDepartName() + "上转患者" + member.getName() + "<a href='/sggg/SgTreatmentReceiveList'>点击查看上转详情</a>", "1");

                sysBaseApi.sendSysAnnouncement(messageDTO);

            }
        }

        // 接诊分配员工
        if (sgTreatmentAssist.getStatus() == 2) {
            SysUser sysUser = this.sysUserService.getOne(new QueryWrapper<SysUser>().eq("id", sgTreatmentAssist.getResponseId()));

            MessageDTO messageDTO = new MessageDTO(loginUser.getUsername(), sysUser.getUsername(), "管理员分配转诊消息提醒", "<a href='/sggg/SgTreatmentTreatingList'>点击查看分配详情</a>", "1");
            sysBaseApi.sendSysAnnouncement(messageDTO);
        }

        // 下转
        if (sgTreatmentAssist.getStatus() == 3) {
            // 接收方机构管理员用户
            List<SysUser> adminUserList = this.sgTreatmentAssistService.getAdminUser(sgTreatmentAssist.getHospitalId());

            for (SysUser u : adminUserList) {

                MessageDTO messageDTO = new MessageDTO(loginUser.getUsername(), u.getUsername(), "下转消息提醒", sysDepart.getDepartName() + "下转患者" + member.getName(), "1");

                sysBaseApi.sendSysAnnouncement(messageDTO);

            }
        }

        sgTreatmentAssistService.updateById(sgTreatmentAssist);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "三高协诊-通过id删除")
    @ApiOperation(value = "三高协诊-通过id删除", notes = "三高协诊-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgTreatmentAssistService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "三高协诊-批量删除")
    @ApiOperation(value = "三高协诊-批量删除", notes = "三高协诊-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgTreatmentAssistService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @ApiOperation(value = "三高协诊-通过id查询", notes = "三高协诊-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgTreatmentAssist> queryById(@RequestParam(name = "id") String id) {
        SgTreatmentAssist sgTreatmentAssist = sgTreatmentAssistService.getById(id);
        if (sgTreatmentAssist == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgTreatmentAssist);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgTreatmentAssist sgTreatmentAssist) {
        return super.exportXls(request, sgTreatmentAssist, SgTreatmentAssist.class, "三高协诊");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgTreatmentAssist.class);
    }

}
